package com.tedu.springhomework.controller;

import com.tedu.springhomework.entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

//spring框架要求，只有被注解@Controller标注的类才是处理业务的类
@Controller
public class UserController {
    public static File userDate;

    static {
        userDate = new File("./users");
        if (!userDate.exists()) {
            userDate.mkdirs();
        }
    }

    //@RequestMapping注解用于标注处理某个具体业务的方法，参数传入的字符串与对应页面中表单的action地址一致
    @RequestMapping("/regUser")
    public void reg(HttpServletRequest request, HttpServletResponse response) {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String ageStr = request.getParameter("age");
        String nickname = request.getParameter("nickname");
        System.out.println(username + "," + password + "," + nickname + "," + ageStr);




        //判断信息格式
        if (username == null || username.trim().isEmpty() ||
                password == null || password.trim().isEmpty() ||
                nickname == null || nickname.trim().isEmpty() ||
                ageStr == null || ageStr.trim().isEmpty() ||
                !ageStr.matches("[\\d]+")) {
            try {
                response.sendRedirect("/reg_info_error.html");
            } catch (IOException e) {
                e.printStackTrace();
            }
            return;
        }

        int age = Integer.parseInt(ageStr);
        User user = new User(username, password, nickname, age);
        File file = new File(userDate,username+".obj");
        if (file.exists()){
            try {
                response.sendRedirect("/have_user.html");
            } catch (IOException e) {
                e.printStackTrace();
            }
            return;
        }

        try (ObjectOutputStream oos = new ObjectOutputStream(
                new FileOutputStream(
                        new File(
                                userDate, username + ".obj")));) {
            oos.writeObject(user);
            response.sendRedirect("/reg_success.html");
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}
